import { defineStore } from 'pinia'
import { ref } from 'vue'
// import { login as loginApi } from '@/api/user'

import { menuRoutes } from '@/router/menuRoutes' // 只导入菜单路由

export const useUserStore = defineStore(
  'user',
  () => {
    const token = ref('')
    const userInfo = ref(null)
    const permissions = ref([])
    const menus = ref([])

    // 登录
    const login = async (loginForm) => {
      // const { token: newToken, userInfo: info } = await loginApi(loginForm)
      // token.value = newToken
      // userInfo.value = info
      console.log(loginForm)
      await getPermissions()
    }

    // 获取权限
    const getPermissions = async () => {
      // 这里应该调用后端接口获取权限
      permissions.value = ['user:view', 'user:edit', 'menu:view']

      // 只使用菜单路由生成菜单
      menus.value = filterAsyncRoutes(menuRoutes)
      console.log(menus.value)
    }

    // 过滤路由配置，生成菜单
    const filterAsyncRoutes = (routes) => {
      return routes.filter((route) => {
        // 过滤掉不需要显示在菜单中的路由
        if (route.meta?.hidden) {
          return false
        }

        // 检查权限
        if (route.meta?.permission) {
          return hasPermission(route.meta.permission)
        }

        // 处理子路由
        if (route.children) {
          route.children = filterAsyncRoutes(route.children)
          // 如果子路由都被过滤掉了，父路由也不显示
          return route.children.length > 0
        }

        return true
      })
    }

    // 登出
    const logout = () => {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      menus.value = []
    }

    // 检查权限
    const hasPermission = (permission) => {
      return permissions.value.includes(permission)
    }

    return {
      token,
      userInfo,
      permissions,
      menus,
      login,
      logout,
      hasPermission,
    }
  },
  {
    persist: {
      // 持久化配置
      key: 'user-store', // 存储的 key
      storage: localStorage, // 存储方式
      paths: ['token', 'userInfo', 'permissions', 'menus'], // 需要持久化的数据
    },
  },
)
